﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;
using System.Data.SqlClient;
using System.Data;

namespace EntityMap.Meta
{
    public class StoredProcedure : ChangeStatement
    {
        protected string _name;

        [XmlAttribute( "name" )]
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }

        public override SqlCommand GetSqlCommand( SqlConnection connection )
        {
            SqlCommand cmd = base.GetSqlCommand( connection );
            cmd.CommandType = CommandType.StoredProcedure;

            return cmd;
        }

        public StoredProcedure()
        {
        }

        public override object Process<T>( Context ctx )
        {
            bool result = false;

            using( SqlConnection conn = new SqlConnection( ctx.Mapper.ConnectionString ) )
            {
                SqlCommand cmd =  new SqlCommand( this.Name, conn );

                cmd.CommandType = CommandType.StoredProcedure;

                if( ctx.ParameterMap != null )
                {
                    cmd.Parameters.AddRange( ctx.ParameterMap.GetSqlParameters( ctx.Parameter ) );
                }   

                conn.Open();

                int effect = cmd.ExecuteNonQuery();

                if( effect > 0 )
                {
                    result = true;
                }
            }

            return result;
        }
    }
}
